package com.bamboocloud.excel;

import com.alibaba.fastjson.JSON;
import com.bamboocloud.dao.UserSequenceDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Service
public class ChangeUserSequence {

    @Resource
    private UserSequenceDao dao;

    @Value("${czt.excel-path}")
    private List<String> excelPathList;

    private Logger logger = LoggerFactory.getLogger(ChangeUserSequence.class);

//    @PostConstruct
    public void init(){


        System.out.println(JSON.toJSONString(excelPathList));
        System.out.println("----");

        if(excelPathList==null || excelPathList.size()==0){
            return;
        }

        for(String fileName : excelPathList){
            readExcel(fileName);
        }
    }

    private void readExcel(String fileName){
        try(
                Workbook workbook = WorkbookFactory.create(new File(fileName))
        ){
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows();
            int dataNum = rowCount - 1;
            logger.info("读取excel文件：{}", fileName);
            for(int i=1;i<rowCount;i++){
                Row row = sheet.getRow(i);
                Cell cell0 = row.getCell(0);
                Cell cell9 = row.getCell(9);
                String username = cell0.getStringCellValue();
                if(StringUtils.isEmpty(username)){
                    break;
                }
                double numericCellValue = cell9.getNumericCellValue();
                int sequence = (int)numericCellValue;
                doChange(username, sequence);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doChange(String username, int sequence){
        logger.info("username: {}, sequence: {}", username, sequence);
        String userId = dao.getUserIdByUsername(username);
        if(StringUtils.isEmpty(userId)){
            logger.error("用户名查询用户id不存在");
            return;
        }

        int i = dao.updateUserSequence(userId, sequence);
        logger.info("修改{}的序号为{}，修改{}条数据",username, sequence, i);
    }
}
